<?php
/*   函数   sub_str($text,   $length)   
**   功能   从文本中截取指定长度字符串,考虑了对中文的处理   
**   参数   $text   要截取的文本   
**   参数   $length   要截取的字符串长度   
*/   
function   sub_str($text,   $length)   
{   
for   ($i=0;   $i<$length;   $i++)   
{   
$chr   =   substr($text,   $i,   1);   
if   (ord($chr)   >   0x80)//字符是中文   
{   
$length++;   
$i++;   
}   

}   
$str   =   substr($text,   0,   $length);     
return   $str;   
}
  
function utf_substr($str,$len)
{
    for($i=0;$i<$len;$i++)
    {
        $temp_str=substr($str,0,1);
        if(ord($temp_str) > 127){
            $i++;
        if($i<$len)    {
            $new_str[]=substr($str,0,3);
            $str=substr($str,3);
            }
        }
    else {
        $new_str[]=substr($str,0,1);
        $str=substr($str,1);
        }
    }
    return join($new_str);
}

function strlen_utf8($str) {
$i = 0;
$count = 0;
$len = strlen ($str);
while ($i < $len) {
$chr = ord ($str[$i]);
$count++;
$i++;
if($i >= $len) break;
if($chr & 0x80) {
$chr <<= 1;
while ($chr & 0x80) {
$i++;
$chr <<= 1;
}
}
}
return $count;
}

function   passport_decrypt($txt,$key){ $txt = passport_key(base64_decode($txt), $key); $tmp = ''; for ($i = 0;  $i < strlen($txt); $i++) { $tmp .=  $txt[$i] ^   $txt[++$i]; } return   $tmp; } function   passport_key($txt,   $encrypt_key)   { $encrypt_key   =   md5($encrypt_key); $ctr   =   0; $tmp   =   ''; for($i   =   0;   $i   <   strlen($txt);   $i++)   {  $ctr   =   $ctr   ==   strlen($encrypt_key)   ?   0   :   $ctr; $tmp   .=   $txt[$i]   ^   $encrypt_key[$ctr++]; } return   $tmp; }function   passport_encode($array)   {  $arrayenc   =   array(); foreach($array   as   $key   =>   $val)   { $arrayenc[]   =   $key.'='.urlencode($val); } return   implode('&',   $arrayenc); }

function mdate()
{
	$tdate=date('Y-m-d H:i:s',strtotime("+0 hours"));
	return $tdate;
}
 
function ShowSC($text)   
{
	global $dbserver,$dbuser, $dbpass,$dbname,$BIAOTOU;
	$hlink = mysql_connect($dbserver, $dbuser, $dbpass);
	if (!$hlink) {
		die(ERR_DB);
	}else{
		mysql_query("set names utf8");
		mysql_select_db($dbname);
		$sql="select * from ".$BIAOTOU."malltype where typecode=".$text;
		$typers = mysql_query($sql);
		while($typerow = mysql_fetch_array($typers)) {
			$typename=$typerow['typename'];
		}
	}
	mysql_close($hlink);
	return   $typename;   
}

//广告输出
function AD($id)   
{
	global $BIAOTOU;
		$sql="select * from ".$BIAOTOU."ad where Id=".$id;
		$adrs = mysql_query($sql);
		while($adrow = mysql_fetch_array($adrs)) {
			$adcontent=$adrow['content'];
		}
	echo $adcontent; 
}

function ShowStar($text){
	switch ($text){
		case "0.1":
		case "0.2":
		case "0.3":
		case "0.4":
		case "0.5":
		case "0.6":
		case "0.7":
		case "0.8":
		case "0.9": $str="5"; break;
		case "1.0":
		case "1.1":
		case "1.2":
		case "1.3":
		case "1.4":$str="10"; break;
		case "1.5":
		case "1.6":
		case "1.7":
		case "1.8":
		case "1.9": $str="15"; break;
		case "1.0":
		case "2.1":
		case "2.2":
		case "2.3":
		case "2.4":$str="20"; break;
		case "2.5":
		case "2.6":
		case "2.7":
		case "2.8":
		case "2.9": $str="25"; break;
		case "3.0":
		case "3.1":
		case "3.2":
		case "3.3":
		case "3.4":$str="30"; break;
		case "3.5":
		case "3.6":
		case "3.7":
		case "3.8":
		case "3.9": $str="35"; break;
		case "4.5":
		case "4.6":
		case "4.7":
		case "4.8":
		case "4.9": $str="45"; break;
		case "5.0": $str="50"; break;
		default: $str="45"; break; 
 	}
	return $str;
}

function ShowShopCat($text){
	switch ($text){
		case "11": $str="电脑硬件/台式机/网络设备"; break;
		case "12": $str="MP3/MP4/iPod/录音笔"; break;
		case "13": $str="手机"; break;
		case "14": $str="女装/流行女装"; break;
		case "15": $str="彩妆/香水/护肤/美体"; break;
		case "16": $str="电玩/配件/游戏/攻略"; break;
		case "17": $str="数码相机/摄像机/图形冲印"; break;
		case "18": $str="运动/瑜伽/健身/球迷用品"; break;
		case "20": $str="古董/邮币/字画/收藏"; break;
		case "21": $str="办公设备/文具/耗材"; break;
		case "22": $str="汽车/配件/改装/摩托/自行车"; break;
		case "23": $str="珠宝/钻石/翡翠/黄金"; break;
		case "24": $str="居家日用/厨房餐饮/卫浴洗浴"; break;
		case "26": $str="装潢/灯具/五金/安防/卫浴"; break;
		case "27": $str="成人用品/避孕用品/情趣内衣"; break;
		case "29": $str="食品/茶叶/零食/特产"; break;
		case "30": $str="玩具/动漫/模型/卡通"; break;
		case "31": $str="箱包皮具/热销女包/男包"; break;
		case "32": $str="宠物/宠物食品及用品"; break;
		case "33": $str="音乐/影视/明星/乐器"; break;
		case "34": $str="书籍/杂志/报纸"; break;
		case "35": $str="网络游戏点卡"; break;
		case "36": $str="网络游戏装备/游戏币/帐号/代练"; break;
		case "37": $str="男装"; break;
		case "1020": $str="母婴用品/奶粉/孕妇装"; break;
		case "1040": $str="ZIPPO/瑞士军刀/饰品/眼镜"; break;
		case "1041": $str="移动联通充值中心/IP长途"; break;
		case "1042": $str="网店装修/物流快递/图片存储"; break;
		case "1043": $str="笔记本电脑"; break;
		case "1044": $str="品牌手表/流行手表"; break;
		case "1045": $str="户外/军品/旅游/机票"; break;
		case "1046": $str="家用电器/hifi音响/耳机"; break;
		case "1047": $str="鲜花速递/蛋糕配送/园艺花艺"; break;
		case "1048": $str="3C数码配件市场"; break;
		case "1049": $str="床上用品/靠垫/窗帘/布艺"; break;
		case "1050": $str="家具/家具定制/宜家代购"; break;
		case "1051": $str="保健品/滋补品"; break;
		case "1052": $str="网络服务/电脑软件"; break;
		case "1053": $str="演出/旅游/吃喝玩乐折扣券"; break;
		case "1054": $str="饰品/流行首饰/时尚饰品"; break;
		case "1055": $str="女士内衣/男士内衣/家居服"; break;
		case "1056": $str="女鞋"; break;
		case "1062": $str="童装/婴儿服/鞋帽"; break;
		case "1082": $str="流行男鞋/皮鞋"; break;
		case "1102": $str="腾讯QQ专区"; break;
		case "1103": $str="IP卡/网络电话/在线影音充值"; break;
		case "1104": $str="个人护理/保健/按摩器材"; break;
		case "1105": $str="闪存卡/U盘/移动存储"; break;
		case "1106": $str="运动鞋"; break;
		case "1122": $str="时尚家饰/工艺品/十字绣"; break;
		case "1153": $str="运动服"; break;
		case "1154": $str="服饰配件/皮带/帽子/围巾"; break;
		default: $str="全部店铺"; break; 
 	}
	return $str;
}

function ck_fxje($commission,$dengji=0){  //输入会员等级，订单总佣金，输出该会员应该得到的返现，等级不输入，按最低返现计算
    $dengji=$dengji?$dengji:1;
	switch($dengji){
		case $dengji<DENGJI1;
		    $myfxbl = FXBL;
		    break;
		case $dengji>=DENGJI1 and $dengji<DENGJI2;
		    $myfxbl = FXBL2;
		    break;
		case $dengji>=DENGJI2 and $dengji<DENGJI3;
		    $myfxbl = FXBL3;
		    break;
		case $dengji>=DENGJI3;
		    $myfxbl = FXBL4;
		    break;
	}
	return round($commission*$myfxbl,2);
}
function mall_ck_fxje($commission,$dengji=0){  //输入会员等级，订单总佣金，输出该会员应该得到的返现，等级不输入，按最低返现计算
    $dengji=$dengji?$dengji:1;
	switch($dengji){
		case $dengji<DENGJI1;
		    $myfxbl = MALLFXBL1;
		    break;
		case $dengji>=DENGJI1 and $dengji<DENGJI2;
		    $myfxbl = MALLFXBL2;
		    break;
		case $dengji>=DENGJI2 and $dengji<DENGJI3;
		    $myfxbl = MALLFXBL3;
		    break;
		case $dengji>=DENGJI3;
		    $myfxbl = MALLFXBL4;
		    break;
	}
	return round($commission*$myfxbl,2);
}

function admin_log($act_name){
	global $BIAOTOU;
    $sql="insert into ".$BIAOTOU."adminlog (`admin_name`, `ip`, `act_name`, `time`) VALUES ('".$_SESSION["adminusername"]."','".$_SERVER["REMOTE_ADDR"]."','".$act_name."','".time()."')";
	mysql_query($sql);
}

function mail_send($to, $title, $html, $from=SMTPUSER,  $usepassword=SMTPPW, $smtp=SMTPHOST) {
	if (!function_exists('fsockopen')) {
        return 'fsockopen函数不可用，联系空间商为您开启此函数';
	}
	if(!class_exists('PHPMailer')){include('class.phpmailer.php');}
	$fromname=$from;
	$usename=$from;
	$mail = new PHPMailer();
	//$mail->SMTPDebug  = 3;
	$mail->CharSet = "UTF-8"; // charset
	$mail->Encoding = "base64";
	$mail->IsSMTP(); // telling the class to use SMTP

	//邮件系统配置
	$mail->SMTPAuth = true;
	$mail->Host = $smtp; // SMTP server
	$mail->Username = $usename; // SMTP account username
	$mail->Password = $usepassword; // SMTP account password

	$mail->From = $from; //必填，发件人Email
	$mail->FromName = $fromname; //必填，发件人昵称或姓名

	$mail->WordWrap = 50; // 自动换行的字数
	$mail->IsHTML(true); // 以 HTML发送

	//主题
	$mail->Subject = (isset ($title)) ? $title : ''; //必填，邮件标题（主题）

	//邮件主体
	$mail->MsgHTML($html);

	//发送地址
	if ($to) {
		$address = explode("|", $to);
		foreach ($address AS $key => $val) {
			$mail->AddAddress($val, "");
		}
	}
	if (!$mail->Send()) {
		$mymsg = "邮件发送失败！可能是邮件服务器设置错误，请联系网站管理员。";
	} else {
		$mymsg = "取回密码邮件已经发送成功，请到您的邮箱收取邮件，如果没有收到邮件请与网站管理员联系。";
	}
	return $mymsg;
}

function form($param){
	$f='';
	foreach($param as $k=>$v){
	    if($k=='action'){
		    $f='<form id="formpost" method="post" action="'.$v.'">';
		}
		else{
			if($k=='orther_web_id') $v=authcode($v,'ENCODE');
		    $f.='<input type="hidden" name="'.$k.'" value="'.$v.'" />';
		}
	}
    $f.="<input type='submit' style='width:0px; height:0px;filter:alpha(opacity=0);opacity:0' value='' /></form><script>document.getElementById('formpost').submit();</script>";
	return $f;
}

function encode_url($iid){
	if(URLKEY==''){return $iid;}
	$baseurl=URLKEY;
	$result=base64_encode($iid."{".$baseurl."}");
	return $result;
}
function decode_url($iid){
	if(URLKEY==''){return $iid;}
	if(!is_numeric($iid)){
	    $baseiid=base64_decode($iid);
	    $exiid=explode("{",$baseiid);
	    $iid=$exiid[0];	
	}
	return $iid;
}

function get_avatar_filepath($uid, $size = 'big', $type = '') {
	$size = in_array($size, array (
		'big',
		'middle',
		'small'
	)) ? $size : 'big';
	$uid = abs(intval($uid));
	$uid = sprintf("%07d", $uid);
	$dir1 = substr($uid, 0, 3);
	$dir2 = substr($uid, 3, 2);
	//$dir3 = substr($uid, 5, 2);
	$typeadd = $type == 'real' ? '_real' : '';
	$avatar_path=$dir1 . '/' . $dir2 . '/' . substr($uid, -2) . $typeadd . "_avatar_$size.jpg";
	if(file_exists(DDROOTPATH.'/upload/avatar/'.$avatar_path)){
	    return $avatar_path;
	}
	else{
	    return 'noavatar_'.$size.'.gif';
	}
}

function get_pic_path($pic){
	$pic=base64_encode($pic);
    if(PICWJT==1 && WJT==1){
	    return 'tbimg/'.$pic.'.jpg';
	}
	else{
	    return 'topic.php?pic='.$pic;
	}
}

function wangwang($nick){
	$nick=urlencode($nick);
    return '<a target="_blank" href="http://amos.im.alisoft.com/msg.aw?v=2&uid='.$nick.'&site=cntaobao&s=2&charset=utf-8" ><img src="http://amos.im.alisoft.com/online.aw?v=2&uid='.$nick.'&site=cntaobao&s=1&charset=utf-8" alert="点击这里给我发消息" /></a>';
}

function html_img($pic_url,$alt='',$class='',$width='',$heigh='',$onerror=''){
	$pic_url=base64_encode($pic_url);
	
	if(PICJM==0){
	    return "<SCRIPT language=javascript>setPic('".$pic_url."','".$width."','".$heigh."','".$alt."','".$class."','".$onerror."');</SCRIPT>";
	}
	elseif(PICJM==1){
		$pic_url=urlencode($pic_url);
	    if($alt!=''){$alt='alt="'.$alt.'"';}
	    if($class!=''){$class='class="'.$class.'"';}
	    if($width>0){$width='width="'.$width.'"';}
	    if($heigh>0){$heigh='heigh="'.$heigh.'"';}
		if($onerror!=''){$onerror='onerror="this.src=\''.$onerror.'\'"';}
		if(PICWJT==0){
		    return "<img ".$onerror." src='topic.php?pic=".$pic_url."' ".$alt." ".$class." ".$width." ".$heigh."/>";
		}
	    else{
		    return "<img ".$onerror." src='tbimg/".$pic_url.".jpg' ".$alt." ".$class." ".$width." ".$heigh."/>";
		}
	}
}

function postform($action,$param){
	$f='<form id="formpost" name="form" method="post" action="'.$action.'">';
	foreach($param as $k=>$v){
		$f.='<input type="hidden" name="'.$k.'" value="'.$v.'" />';
	}
    $f.="<input type='submit' style='width:0px; height:0px;filter:alpha(opacity=0);opacity:0' value='' /></form><script>document.getElementById('formpost').submit();</script>";
	return $f;
}

function str_del_last($str){
	$newstr = substr($str,0,strlen($str)-1);
	return $newstr;
}

function add_uid_jump_url($url, $uid = 0) {
	$param=array();
	$p='';
	if(strpos($url,'s8.taobao.com')!==false){
	    $u='unid';
		$lm='alimama';
	}
	elseif(strpos($url,'taobao')!==false){
	    $u='u';
		$lm='alimama';
	}
	elseif(strpos($url,'chanet')!==false){
	    $u='u';
		$lm='chanet';
	}
	elseif(strpos($url,'yiqifa')!==false){
	    $u='e';
		$lm='yiqifa';
	}
	elseif(strpos($url,'linktech')!==false){
	    $u='u_id';
		$lm='linktech';
	}
	elseif(strpos($url,'duomai')!==false){
	    $u='euid';
		$lm='duomai';
	}
    if(strstr($url,'?')){
    	$arr=explode('?',$url);
    	parse_str($arr[1],$param);
    	$param[$u]=$uid;
    	foreach($param as $k=>$v){
			if($k!=''){
				if($lm=='alimama' || $lm=='duomai' || $lm=='linktech'){
				    $p.=$k.'='.urlencode($v).'&';
				}
			    else{
				    $p.=$k.'='.$v.'&';
				}
			}
    	}
    	$url=str_del_last($arr[0].'?'.$p);
    }
    else{
    	$url=$url.'?'.$u.'='.$uid;
    }

	return $url;
}

function deldir($dir) {
	$dh = opendir($dir);
	while ($file = readdir($dh)) {
		if ($file != "." && $file != "..") {
			$fullpath = $dir . "/" . $file;
			if (!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}
	closedir($dh);
}

function get_client_ip()
{
	$ip = $_SERVER['REMOTE_ADDR'];
	if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP']))
	{
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	}
	elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches))
	{
		foreach ($matches[0] AS $xip)
		{
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip))
			{
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}

function authcode($string, $operation = 'DECODE', $key='', $expiry = 0) {
	if($key==''){
	    global $dbpass;
		$key=$dbpass;
	}
	$ckey_length = 4; // 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥

	//取消UC_KEY，改为必须传入$key才能运行
	if (empty ($key)) {
		exit ('PARAM $key IS EMPTY! ENCODE/DECODE IS NOT WORK!');
	} else {
		$key = md5($key);
	}

	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microTIME), - $ckey_length)) : '';

	$cryptkey = $keya . md5($keya . $keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry +TIME : 0) . substr(md5($string . $keyb), 0, 16) . $string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array ();
	for ($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for ($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for ($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a +1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if ($operation == 'DECODE') {
		if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - TIME > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace('=', '', base64_encode($result));
	}
}

function get_tao_id($url, $tao_id_arr) {
	$query=preg_replace('/(.*?)\?/','',$url);
    parse_str($query,$a);
	$c=count($tao_id_arr);
	for ($i = 0; $i < $c; $i++) {
		if (array_key_exists($tao_id_arr[$i], $a)) {
			if ($a[$tao_id_arr[$i]] != '') {
				return $a[$tao_id_arr[$i]];
			}
		}
	}
}

function reg_taobao_url($url){
    if(preg_match('/(taobao\.com|tmall\.com)/',$url)==1){
		return 1;
	}
	else{
	    return 0;
	}
}
?>